<template>
	<view class="content">
		<top-bar>
			<template #left>
				<image src="../../static/images/login/back.png" @tap="back" style="width: 44rpx;height: 44rpx;"></image>
			</template>
			<template #center>
				<text style="font-size: 40rpx;">{{user.name}}</text>
			</template>
			<template #right>
				<view @tap="toGarllery(user._id)">
					<view>
						<image :src="user.imgrul" mode="" style="width: 70rpx;height: 70rpx;border-radius: 8rpx;">
						</image>
					</view>
				</view>
			</template>
		</top-bar>
		<view class="main">
			<!-- 使用scroll-view时 该标签的高度不能设置为百分数，否则滚动效果会失效 -->
			<!-- -->
			<view class="chat-tip" view v-if="tips">
				<view v-if="tips">
					tips:<br /><text v-html="tips"></text>
				</view>
				<button @tap="tips=''">关闭</button>
			</view>
			<scroll-view class="chat" scroll-y="true" :style="{height:scrollHeight+'px'}"
				:scroll-into-view="scrollToView">
				<view class="chat-main" :style="{paddingBottom:autoIptHeight+'px'}" @tap="explain">
					<view class="chat-ls" v-for="(item,index) in msgs" :key="item.id" :id="`msg${index}`">

						<view class="msg-m msg-left" v-if="item.fromId==friendID">
							<image :src="item.imgurl" @error="imgLoadingError" @tap="toGarllery(user._id)"
								class="user-img">
							</image>
							<view>

								<view class="message" v-if="item.types==0">
									<view class="msg-text" :data-msg="item.message" :data-index="index">
										{{item.message}}
									</view>
								</view>
								<view class="message" v-if="item.types==1">
									<image :src="item.message" class="msg-img" mode="widthFix"
										@tap="previewImg(item.message)"></image>
								</view>
								<view class="message voice" v-if="item.types==2">
									<view class="msg-text" @tap="playAudio(item.message)">
										<image src="../../static/images/cheat/voice_left.png" mode=""></image>
										<view class="tip_left">{{item.message.time}}''</view>
									</view>
								</view>
								<view class="message mapMsg" @tap="openMap(item.message)" v-if="item.types==3">
									<view class="msg-text">
										<view class="mapMsg-location">{{item.message.location}}</view>
										<view class="mapMsg-address">{{item.message.address}}</view>
										<view class="mapMsg-map" style="">
											<image style="height: 100%;width: 100%;" :src="
											returnBaiduMapImg(item.message)">
											</image>
										</view>
									</view>
								</view>
								<view class="chat-time" v-if="item.time">
									{{FormDataChat(item.time)}}
								</view>
							</view>
						</view>
						<!-- 这里挖坑了，群聊怎么展示？？ -->
						<view class="msg-m msg-right" v-else>
							<image :src="item.imgurl" @error="imgLoadingError" @tap="toGarllery(MasterUserID)"
								class="user-img">
							</image>
							<view class="test">
								<view class="message" v-if="item.types==0">
									<view class="msg-text" :data-msg="item.message" :data-index="index">
										{{item.message}}
									</view>
								</view>
								<view class="message" v-if="item.types==1">
									<image :src="item.message" class="msg-img" mode="widthFix"
										@tap="previewImg(item.message)"></image>
								</view>
								<view class="message voice" v-if="item.types==2">
									<view class="msg-text" @tap="playAudio(item.message)">
										<view class="tip_right">{{item.message.time}}''</view>
										<image src="../../static/images/cheat/voice_right.png" mode=""></image>
									</view>
								</view>
								<view class="message mapMsg" @tap="openMap(item.message)" v-if="item.types==3">
									<view class="msg-text" style="">
										<view class="mapMsg-location">{{item.message.location}}</view>
										<view class="mapMsg-address">{{item.message.address}}</view>
										<view class="mapMsg-map">
											<image style="height: 100%;width: 100%;"
												:src="returnBaiduMapImg(item.message)">
											</image>
										</view>
									</view>
								</view>
								<view class="chat-time" v-if="item.time">
									{{FormDataChat(item.time)}}
								</view>
							</view>
						</view>
					</view>
				</view>
				<view class="padbt"></view>
			</scroll-view>
		</view>
		<submit @sendMsg="sendMsg" @getIptHeight="getIptHeight"></submit>
	</view>
</template>

<script>
	import util from '../../commons/js/util.js'
	import submit from '../../components/submit/submit.vue'
	import config from "../../commons/config.js"
	import {
		RuntimeServerUrl
	} from "../../commons/getRuntimeEnv.js"
	import {
		clearUnreadMsgApi
	} from "../../api/getInfo.js"
	const innerAudioContext = uni.createInnerAudioContext();
	console.log(RuntimeServerUrl, ".RuntimeServerUrl");
	export default {
		data() {
			return {
				isKeyBoard: true,
				message: '',
				//用户显示
				user: '',
				tips: '',
				//主人ID
				MasterUserID: '',
				MasterImage: '',
				friendID: '',
				// 聊天数据
				msgs: [],
				//聊天图片
				imgMsg: [],
				scrollToView: '',
				// 子组件的input面板高度 将内容撑大 通过子组件传递过来
				autoIptHeight: 0,
				// 最大时间
				oldTime: new Date(),
				//scrollview高度  获取设备高度
				scrollHeight: 0,
				//是否在播放
				//地图截图获取地址加key
				baiduMapBase: 'https://apis.map.qq.com/ws/staticmap/v2/?key=LSWBZ-P53CU-V5NV2-BMF5D-QJQBS-66BTW'
			}
		},
		components: {
			submit
		},
		onReady() {
			let _this = this;
			uni.getSystemInfo({ //调用uni-app接口获取屏幕高度
				success(res) { //成功回调函数
					let wHeight = res.windowHeight //windoHeight为窗口高度，主要使用的是这个
					let titleH = uni.createSelectorQuery().select(".chat"); //想要获取高度的元素名（class/id）
					titleH.boundingClientRect(data => {
						//单位是px
						_this.scrollHeight = wHeight - data.top //计算高度：元素高度=窗口高度-元素距离顶部的距离（data.top）
					}).exec()
				}
			})
		},
		onLoad(option) {
			this.MasterUserID = uni.getStorageSync('userid'),
				this.friendID = option.id,
				console.log(this.MasterUserID, this.friendID);
			this.getExhibition(option.id)
			//获取聊天数据
			this.getMsg()
			this.getMasterImage(this.MasterUserID)

			// 监听的socket都要放在onLoad中
			// 接受私发的消息 这个事件只有在 socket指定socket生效
			// todosocket
			this.socketMsgAdnPushShow()

		},
		onShow() {},
		onUnload() {
			innerAudioContext.stop()
		},
		methods: {
			//解释用户聊天
			explain(e) {
				let {
					index
				} = e.target.dataset
				let explainData = []
				this.msgs.slice(index - 10, index).map(item => {
					if (item.id != this.MasterUserID) {
						explainData.push({
							role: "user",
							content: "好友说:" + item.message
						})
					} else {
						explainData.push({
							role: "user",
							content: "我说:" + item.message
						})
					}
				})
				this.gen([{
						role: "system",
						content: "总结对话，分析，应该回复什么内容"
					},
					...explainData,
					{
						role: "user",
						content: "l say:我应该回什么"
					}

				])
				console.log(explainData, "eeeee");
				console.log(index, "eeeee");
			},
			//
			gen(question) {
				const url = new URL("/gen", RuntimeServerUrl)
				url.searchParams.set("prompt", JSON.stringify(question))
				this.eventSource = new EventSource(url)
				this.eventSource.addEventListener('message', (event) => {
					console.log("message", event);
					console.log("message", event.data);
					if (event.data != "DONE") {
						this.tips += event.data
					} else {
						this.generating = false
						this.eventSource.close()
					}
				});

				// 监听 error 事件，处理连接错误
				this.eventSource.addEventListener('error', function(error) {
					console.error('EventSource encountered an error:', error);
				});
				this.eventSource.addEventListener('close', function() {
					console.log('close');
				});
			},
			// 图片错误显示
			imgLoadingError() {
				console.log(event.detail, "出错了");
			},
			returnBaiduMapImg({
				latitude,
				longitude
			}) {
				let url =
					`${this.baiduMapBase}&size=400*300&center=${latitude},${longitude}&zoom=16&markers=color:blue|${latitude},${longitude}`
				// console.log(url);
				return url
			},
			FormDataChat(e) {
				return util.formatDate(new Date(e), 1)
			},
			//根据用户id得到顶部用户数据，
			async getExhibition(id) {
				let {
					data
				} = await util.request({
					url: "/user/detail",
					method: "post",
					data: {
						id,
					}
				})
				data.result.imgrul = RuntimeServerUrl + data.result.imgrul
				// data.result.explain='dfgsgfd'
				data.result.explain = data.result.explain || ''
				this.user = data.result
				// console.log(this.user, 'this');
			},
			//获取主用户的头像
			async getMasterImage(id) {
				let {
					data
				} = await util.request({
					url: "/user/detail",
					method: "post",
					data: {
						id,
					}
				})
				this.MasterImage = RuntimeServerUrl + data.result.imgrul
				// console.log(,'data');
			},
			//聊天数据展示onLoad执行，
			// 获取聊天数据 需要uid,fid
			async getMsg() {
				let msg = await util.request({
					url: "/chat/getmessagepage",
					method: "POST",
					data: {
						uid: this.MasterUserID,
						fid: this.friendID,
						// nowPage,
						// pageSize
					}
				}).then(res => {
					// console.log(res.data);
					if (res.data.status == 200)
						return Promise.resolve(res.data.result)
					else
						return Promise.resolve([])
				}).catch(err => {
					// console.log(err);
				})
				let tempmsg = []
				console.log("地图信息查看", msg);
				msg.forEach((item, index) => {
					//头像链接 组成
					item.imgurl = RuntimeServerUrl + item.imgurl
					// 消息类型是图片
					if (item.types == 1) {
						item.message = RuntimeServerUrl + item.message
						//用户预览的图片地址数组
						this.imgMsg.unshift(item.message)
					}
					//语音 也要加上地址
					if (item.types == 2) {
						item.message = RuntimeServerUrl + item.message
					}
					//如果消息是地图 传回来的是JSON字符串
					if (item.types == 3) {
						console.log(item.message, "地址");
						item.message = JSON.parse(item.message)
					}
					//最后的消息显示时间
					// let t = util.spaceTime(this.oldTime, item.time)
					// // console.log(t);
					// if (t) {
					// 	// 如果存设置oldTime
					// 	this.oldTime = t
					// }
					// item.time = t
					// console.log(item.fromId,'item');
					// 数据结构类似于栈 栈顶是0，倒过来的栈
					tempmsg.unshift(item)
				})
				console.log(tempmsg, "tempmsg");
				this.msgs = tempmsg
				// console.log(this.msgs,'this.msgs');
				this.toBottom()
			},
			// 预览图片
			previewImg(item) {
				// console.log(item);
				// console.log(this.imgMsg);
				let index = 0;
				this.imgMsg.map((it, i) => {
					if (it.includes(item))
						index = i
				})
				uni.previewImage({
					// 图片链接地址数组
					urls: this.imgMsg,
					// 展示图片的索引
					current: index,
					longPressActions: {
						// 预览图片时 长按图片 显示三个选项
						itemList: ['发送给朋友', '保存图片', '收藏'],
						success: function(data) {
							// console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
						},
						fail: function(err) {
							// console.log(err.errMsg);
						}
					}
				});
			},

			//返回上一层
			back() {
				uni.navigateBack()
				clearUnreadMsgApi(this.MasterUserID, this.friendID).then(res => {
					console.log("清空未读消,成功");
				}).catch(err => {
					throw new Error(err)
				})
			},
			//去详情页面
			toGarllery(id) {
				// console.log(id);
				uni.navigateTo({
					url: `/pages/userGarllery/userGarllery?id=${id}`
				})
			},
			// 传入数据data 中解构出这两个项目 音频数据message：{voice,time}
			sendMsg({
				message,
				types
			}) {
				// console.log(message,types,"nihao,wodiaonma");
				//间隔时间5分钟
				let nowTime = new Date().getTime()
				// let t = util.spaceTime(this.oldTime, nowTime)
				// // console.log(t);
				// if (t) {
				// 	// 如果存设置oldTime
				// 	this.oldTime = t
				// }
				// nowTime = t
				let data = {
					imgurl: this.MasterImage,
					message,
					types,
					time: nowTime,
				}
				// console.log(this.imgMsg,'imgMsg');

				//展示数据通过socket返回数据

				//如果是文字发送
				// console.log(data, '地图信息');
				if (data.types == 0 || data.types == 3) {
					// console.log(data,'地图');
					this.SendMsgBySocket(data)
					this.msgs.push(data)
					this.toBottom()
				}
				//如果是图片 需要传入预览数组中
				if (types == 1) {
					const date = new Date();
					let url = `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
					// debugger
					uni.uploadFile({
						url: RuntimeServerUrl + '/upload/upload',
						// 文件路径
						filePath: message,
						name: 'file',
						header: {
							"Authorization": 'Bearer ' + uni.getStorageSync('token'),
						},
						// 携带数据请求体
						formData: {
							url: url,
							id: this.MasterUserID
						},
						success: (uploadFileRes) => {
							//上传成功 才将图片加入到
							if (uploadFileRes.statusCode == 200) {
								let data1 = {
									message: JSON.parse(uploadFileRes.data).userImgProfile,
									imgurl: this.MasterImage,
									types: 1
								}
								// console.log(data1, 'uploadFileRes');
								this.imgMsg.push(message)
								//将数据处理好后 发送给socket
								this.SendMsgBySocket(data1)
								// console.log(uploadFileRes.data,'uploadFileRes.data');	
								this.msgs.push(data)
								this.toBottom()
							} else {
								uni.showToast({
									title: "网络繁忙，请稍后重试",
									icon: 'none',
									duration: 1500
								})
							}
						}
					})
				}
				//如果是音频文件
				if (types == 2) {
					const date = new Date();
					let url = `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
					// debugger
					uni.uploadFile({
						url: RuntimeServerUrl + '/upload/upload',
						// 文件路径
						filePath: message.voice,
						name: 'file',
						// 携带数据请求体
						formData: {
							url: url,
							id: this.MasterUserID
						},
						success: (uploadFileRes) => {
							// console.log(uploadFileRes.data,'uploadFileRes');
							let data1 = {
								message: JSON.parse(uploadFileRes.data).userImgProfile,
								imgurl: this.MasterImage,
								types: 2
							}
							// console.log(data1, 'uploadFileRes');
							//将数据处理好后 发送给socket
							this.SendMsgBySocket(data1)
							// console.log(uploadFileRes.data,'uploadFileRes.data');
							this.msgs.push(data)
							this.toBottom()
						}
					})
				}
				console.log(data, "传输数据");
				// console.log(this.imgMsg,'lunbo');
				// this.msgs.push(data)
				// debugger
				// this.toBottom()
			},
			//
			//@params e object 消息数据
			SendMsgBySocket(e) {
				//通过this.type(0/1)判断是个人还是群聊？？暂时没有做群聊 
				if ("private") {
					// this.socket.emit("private chat",e,this.MasterUserID,this.friendID,)
					// 发送一个私聊事件 点击发送时需要携带指定的数据
					this.$socket.emit("privateMsg", {
						msg: e,
						fromId: this.MasterUserID,
						toId: this.friendID
					})
					//TODO 留言 
					util.request({
						url: '/user/sendmsg',
						method: "post",
						data: {
							uid: this.MasterUserID,
							fid: this.friendID,
							msg: e.message,
							type: e.types
						}
					}).then(res => {
						console.log(res);
					})
				}
			},
			//接收socket传回数据并 push到页面展示数据中
			// todosocket
			socketMsgAdnPushShow() {
				let that = this
				this.$socket.on("receivePrivateMsg", ({
					fromId,
					message,
					imgurl,
					types
				}) => {
					//是不是发给这个好友的 判断
					if (fromId == this.friendID) {
						//间隔时间5分钟
						let nowTime = new Date().getTime()
						// let t = util.spaceTime(this.oldTime, nowTime)
						// // console.log(t);
						// if (t) {
						// 	// 如果存设置oldTime
						// 	this.oldTime = t
						// }
						// nowTime = t
						// console.log(message, types, 'message,types'); //🤣 0  message,types
						let data = {
							fromId,
							imgurl,
							message,
							types,
							time: nowTime,
							id: new Date().getTime() + "E" + Math.ceil(Math.random() * 10)
						}
						//图片进行处理
						if (types == 1 || types == 2) {
							data.message = RuntimeServerUrl + message,
								data.id = new Date().getTime() + "E" + Math.ceil(Math.random() * 10)

							//如果是图片 那么需要插入数据用来展示
							types == 1 && this.imgMsg.push(RuntimeServerUrl + message)
						}
						if (types == 3) {
							// console.log(message.message, 'message.message');
							data.id = new Date().getTime() + "E" + Math.ceil(Math.random() * 10)
						}
						// console.log(data, 'receive');
						this.msgs.push(data)
						this.toBottom()
					}
				})
			},

			// 拿到子组件传递过来的高 设置给main-chat
			getIptHeight(val) {
				// console.log(val,'getIptHeight');
				this.toBottom()
				this.autoIptHeight = val
				// console.log(this.autoIptHeight,'this.autoIptHeight');
			},
			toBottom(e) {
				// 这个值变化了才会触发动画
				this.scrollToView = ''
				this.$nextTick(function() {
					// 没有效果
					this.scrollToView = `msg${(this.msgs.length-1)}`
					// console.log(this.scrollToView);
				}, 100)
			},
			playAudio(item) {
				//事件绑定都在vie视图上时，event显示的是手机视图上的一些参数
				// let timer;
				// clearTimeout(timer)
				// //点击播放 添加播放样式 播放完毕移除样式
				// console.log(item.time,'音频时长');
				// //曹尼玛，event可以拿到当前点击的对象
				// let amt_flags=event.currentTarget.children
				// // console.log(event.currentTarget.children[0]);
				// //播放添加动画

				// amt_flags[0].classList.add('isplay')
				// amt_flags[1].classList.add('isplay')
				// timer=setTimeout(()=>{
				// 	amt_flags[0].classList.remove('isplay')
				// 	amt_flags[1].classList.remove('isplay')
				// },(item.time)*1000)
				// console.log(item.voice, '点击播放语音');
				innerAudioContext.src = item.voice;
				innerAudioContext.play();
			},
			//经纬度
			openMap({
				latitude,
				longitude
			}) {
				//点击当前元素传入 聊天数据message={地点信息}
				uni.openLocation({
					latitude: latitude,
					longitude: longitude,
					success: function() {
						// console.log('success');
					}
				});
			}

		}
	}
</script>

<style lang="scss">
	.content {
		padding-top: var(--status-bar-height);
		height: calc(100vh- 88rpx + var(--status-bar-height));
		// height: 100vh;
		overflow: hidden;
	}

	.main {
		position: relative;
		// margin-top: var(--status-bar-height);
		margin-top: calc(88rpx + var(--status-bar-height));
		height: 85vh;

		.chat-tip {
			font-size: 28rpx;
			padding: 10rpx 30rpx;
			border-radius: 10px;
			width: 50%;
			max-height: 80%;
			overflow-y: scroll;
			min-height: 88rpx;
			background-color: #62ff60;
			position: absolute;
			transform: translate(-50%, -50%);
			top: 50%;
			left: 50%;
			z-index: 1000;

			button {
				font-size: 26rpx;
				margin: 16rpx auto 0 auto;
				width: 30%;

				&:hover {
					background-color: red;
				}
			}
		}

		.chat {

			// height: 1350rpx; 
			.chat-main {
				padding: 0rpx 32rpx 0rpx 32rpx;
				display: flex;
				flex-direction: column;
				margin-top: 40px;
			}

			// 占位
			.padbt {
				height: 100rpx;
				width: 100%;
			}

			.chat-ls {
				.chat-time {
					font-size: 24rpx;
					color: rgba(39, 40, 50, 0.30);
				}

				//左右公用的数据
				.msg-m {
					display: flex;
					padding: 20rpx 0;

					.user-img {
						flex: none;
						width: 80rpx;
						height: 80rpx;
						border-radius: 20rpx;
					}

					.message {
						max-width: 480rpx;
						/*这两行代码可以解决大部分场景下的换行问题*/
						word-break: break-all;
						word-wrap: break-word;
						/*但在有些场景中，还需要加上下面这行代码*/
						white-space: normal;

						.msg-text {
							font-size: 32rpx;
							color: $uni-text-color;
							line-height: 44rpx;
							padding: 18rpx 24rpx;

							image {
								display: inline-block;
								line-height: 16rpx;
								width: 40rpx;
								height: 40rpx;
							}
						}

						.msg-img {
							max-width: 400rpx;
							border-radius: 20rpx;
						}
					}

					.voice {
						image {
							padding-top: 10rpx;
						}

						// .msg-text{
						// 	float: right;
						// 	width: 100rpx;
						// }
						.tip_left {
							// animation: paly 0.5s infinite alternate;
							float: right;
							line-height: 28rpx;
						}

						.tip_right {
							float: left;
							line-height: 28rpx;
						}

					}

					.mapMsg {
						.msg-text {
							max-width: 440rpx;
							width: 400rpx;
							background-color: #fff;
							padding: 0;

							.mapMsg-location {
								padding: 10rpx 20rpx 0rpx 20rpx;
								font-size: 36rpx;
								letter-spacing: 4rpx;
								// width: 95%;
								height: 100%;
							}

							.mapMsg-address {
								padding: 0rpx 20rpx 10rpx 20rpx;
								font-size: 26rpx;
								color: #a2a2a2;
								display: -webkit-box;
								-webkit-box-orient: vertical;
								-webkit-line-clamp: 1;
								overflow: hidden;
							}

							.mapMsg-map {
								// border: 1px solid;
								height: 250rpx;
								width: 100%;

								image {
									border-bottom-left-radius: 16rpx;
									border-bottom-right-radius: 16rpx;
								}
							}
						}
					}
				}

				.msg-left {
					flex-direction: row;

					.msg-text {
						margin-left: 16rpx;
						background-color: #d0d0d0;
						border-radius: 0 20rpx 20rpx 20rpx;
					}

					.msg-img {
						margin-left: 16rpx;
					}
				}

				.msg-right {
					flex-direction: row-reverse;

					.msg-text {
						margin-right: 16rpx;
						background-color: #FFf260;
						;
						border-radius: 20rpx 0rpx 20rpx 20rpx;
					}

					.msg-img {
						margin-right: 16rpx;
					}
				}
			}
		}
	}

	.isplay {
		animation: paly 0.2s infinite alternate;
	}

	@keyframes paly {
		from {
			transform: scale(0.9, 0.9);
		}

		to {
			transform: scale(1.2, 1.2);
		}
	}
</style>